#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SYM1    'I'
#define SYM5    'V'
#define SYM10   'X'
#define SYM50   'L'
#define SYM100  'C'
#define SYM500  'D'
#define SYM1000 'M'

#define SYM4   "IV"
#define SYM9   "IX"
#define SYM40  "XL"
#define SYM90  "XC"
#define SYM400 "CD"
#define SYM900 "CM"

#define BUF_SIZE 20
char *intToRoman(int num) {
    char *buf = (char *)malloc(BUF_SIZE);
    memset(buf, BUF_SIZE, 0);

    int idx = 0;

    int cur = num / 1000;
    num     = num % 1000;
    for (int i = 0; i < cur; i++)
        buf[idx++] = SYM1000;

    cur = num / 100;
    num = num % 100;
    if (cur < 4)
        for (int i = 0; i < cur; i++)
            buf[idx++] = SYM100;
    else if (cur == 4)
        buf[idx++] = SYM400[0], buf[idx++] = SYM400[1];
    else if (cur < 9) {
        buf[idx++] = SYM500;
        for (int i = 5; i < cur; i++)
            buf[idx++] = SYM100;
    } else if (cur == 9)
        buf[idx++] = SYM900[0], buf[idx++] = SYM900[1];

    cur = num / 10;
    num = num % 10;
    if (cur < 4)
        for (int i = 0; i < cur; i++)
            buf[idx++] = SYM10;
    else if (cur == 4)
        buf[idx++] = SYM40[0], buf[idx++] = SYM40[1];
    else if (cur < 9) {
        buf[idx++] = SYM50;
        for (int i = 5; i < cur; i++)
            buf[idx++] = SYM10;
    } else if (cur == 9)
        buf[idx++] = SYM90[0], buf[idx++] = SYM90[1];

    cur = num;
    if (cur < 4)
        for (int i = 0; i < cur; i++)
            buf[idx++] = SYM1;
    else if (cur == 4)
        buf[idx++] = SYM4[0], buf[idx++] = SYM4[1];
    else if (cur < 9) {
        buf[idx++] = SYM5;
        for (int i = 5; i < cur; i++)
            buf[idx++] = SYM1;
    } else if (cur == 9)
        buf[idx++] = SYM9[0], buf[idx++] = SYM9[1];

    return buf;
}

int main(void) {
    int nums[] = {3, 4, 9, 40, 58, 1994};

    printf("整数转罗马数字: 这个没办法释放内存，会爆堆\n\n");

    for (int i = 0; i < sizeof(nums) / sizeof(int); i++)
        printf("%d: %s\n", nums[i], intToRoman(nums[i]));
    return 0;
}